/*
 * Copyright 2010-2016 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jetbrains.kotlin.script

import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import java.io.File
import java.io.InputStream

fun <TF: Any> getFileName(file: TF): String = when (file) {
    is PsiFile -> file.originalFile.name
    is VirtualFile -> file.name
    is File -> file.name
    else -> throw IllegalArgumentException("Unsupported file type $file")
}

fun <TF: Any> getFilePath(file: TF): String = when (file) {
    is PsiFile -> file.originalFile.run { virtualFile?.path ?: name } // TODO: replace name with path of PSI elements
    is VirtualFile -> file.path
    is File -> file.canonicalPath
    else -> throw IllegalArgumentException("Unsupported file type $file")
}

fun <TF: Any> isValidFile(file: TF): Boolean = when (file) {
    is PsiFile -> file.isValid
    is VirtualFile -> file.isValid
    is File -> file.exists() && file.isFile
    else -> throw IllegalArgumentException("Unsupported file type $file")
}

fun <TF: Any> getFile(file: TF): File? = when (file) {
    is PsiFile -> file.originalFile.run { File(virtualFile?.path) }
    is VirtualFile -> File(file.path)
    is File -> file
    else -> throw IllegalArgumentException("Unsupported file type $file")
}

fun <TF: Any> getFileContents(file: TF): CharSequence = when (file) {
    is PsiFile -> file.viewProvider.contents
    is VirtualFile -> file.inputStream.reader(charset = file.charset).readText()
    is File -> file.readText()
    else -> throw IllegalArgumentException("Unsupported file type $file")
}

fun <TF: Any> getFileContentsStream(file: TF): InputStream = when (file) {
    is PsiFile -> file.viewProvider.contents.toString().byteInputStream()
    is VirtualFile -> file.inputStream
    is File -> file.inputStream()
    else -> throw IllegalArgumentException("Unsupported file type $file")
}

